package com.leetao.netty.server;

import com.leetao.netty.config.NettyConfig;
import com.leetao.netty.core.WebSocketServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.net.ssl.SSLException;
import java.security.cert.CertificateException;

/**
 * netty server
 * @author 菅江晖
 * @date 2021/4/15 - 15:55
 */
@Component
public class WebSocketServer {
    static final boolean SSL = System.getProperty("ssl") != null;
    @Autowired
    WebSocketServerInitializer nettyServerInitializer;

    @Autowired
    NettyConfig nettyConfig;

    public void start() throws CertificateException, SSLException, InterruptedException {
       /*
       请自行实现ssl

       // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }
        */
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(nettyServerInitializer);

            Channel ch = b.bind(nettyConfig.getPort()).sync().channel();

            System.out.println("Open your web browser and navigate to " +
                    (SSL? "https" : "http") + "://127.0.0.1:" + nettyConfig.getPort() + nettyConfig.getWsPath());

            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
